import ajax from "@/utils/ajax";
import axios from "axios";
import echarts from "echarts";
let proportion = null;
let proptime = null
let color = [
  "rgba(208,169,0,0.3)",
  "rgba(255,83,84,0.3)",
  "rgba(107,188,48,0.3)",
  "rgba(6,167,248,0.3)",
  "rgba(150,77,255,0.3)",
]
let colorhover = [
  "rgb(208,169,0)",
  "rgb(255,83,84)",
  "rgb(107,188,48)",
  "rgb(6,167,248)",
  "rgb(150,77,255)",
]
export default {
  data() {
    return {
      Dateperiod: "week",
      proportiondata: {
        series: [
        ],
      },
      proportionindex: 0,
      overviewdata: {
        value: 0,
        name: "",
        allprod: 0,
        opprod: 0
      },
      overviewwavetop: 0,
      prodnum: {},
      operationTotal: null,
      electricity: {
        day: 0,
        week: 0,
        month: 0,
        year: 0,
        dayavg: 0,
      },
      watermeter: {
        day: 0,
        week: 0,
        month: 0,
        year: 0,
        dayavg: 0,
      },
      temperature: {
        max: 0,
        min: 0
      },
      isele: 0,
      WaterTotalRankingdata:[]
    };
  },
  created() { },
  beforeDestroy() {

    clearInterval(proptime)
    proptime = null
  },
  mounted() {
    this.initial()
    this.getProbeTotaldata()
    this.getOperationTotaldata()
    this.getweekeledata();
    this.getworkele();
    this.getWaterAlldata()
    this.geproportiondata();

  },
  methods: {
    //用水用电切换
    eleandwaterchange() {
      this.isele = this.isele == 0 ? 1 : 0
      this.Dateperiod = 'week'
      this.getelerankdata()
      this.getwatermeterdata()
    },
    //用电周月年
    getEleAlldata() {
      ajax.get({
        url: this.$API.getEleAll + this.$store.getters.user.id,
        success: (res) => {
          this.electricity.week = parseFloat(res.data.week / 1000) + parseFloat(this.electricity.day)
          this.electricity.month = parseFloat(res.data.month / 1000) + parseFloat(this.electricity.day)
          this.electricity.year = parseFloat(res.data.year / 1000) + parseFloat(this.electricity.day)
        },
      })

    },
    //用水周月年
    getWaterAlldata() {

      ajax.get({
        url: this.$API.getWaterTotalAll + this.$store.getters.user.id + `?end=${getFormatDatezhuanh(new Date()).slice(0, 10)}&start=${getFormatDatezhuanh(new Date()).slice(0, 10)}&type=1`,
        success: (res) => {
          this.watermeter.week = res.data.week
          this.watermeter.month = res.data.month
          this.watermeter.year = res.data.year
        },
      })

    },
    //初始化固定数据
    initial() {
      let startDay, endDay, data
      let month = new Date().getMonth() == 0 ? 12 : new Date().getMonth()
      data = getMonthopandend(`${new Date().getMonth() == 0 ? new Date().getFullYear() - 1 : new Date().getFullYear()}-${month}-1`)
      startDay = data[0].slice(0, 10)
      endDay = data[1].slice(0, 10)
      //用水量日均
      ajax.get({
        url: this.$API.getWaterTotal + this.$store.getters.user.id + `?end=${endDay}&start=${startDay}&type=1`,
        success: (res) => {
          let total = 0
          total = Object.values(res.data).reduce((old, now) => {
            return old + now
          }, 0)
          this.watermeter.dayavg = (total / Object.values(res.data).length).toFixed(1)
        },
      })
      //用电量日均
      ajax.get({
        url: this.$API.getEleAllByDay + this.$store.getters.user.id + `?end=${endDay}&start=${startDay}&type=1`,
        success: (res) => {
          let total = 0
          total = Object.values(res.data).reduce((old, now) => {
            return parseFloat(old) + parseFloat(now)
          }, 0)
          this.electricity.dayavg = ((total / Object.values(res.data).length) / 1000).toFixed(1)
        },
      })
      //环境温度
      ajax.get({
        url: this.$API.getAmbientTemperature + this.$store.getters.user.id,
        success: (res) => {
          this.temperature = res.data
        },
      })
      //获取用水量统计排行(昨天的用水量)
      ajax.get({
        url: this.$API.getWaterTotalRanking + this.$store.getters.user.id,
        success: (res) => {
          if (res.data.length > 0) {
            this.WaterTotalRankingdata = []
            let total=0
            for (let item of res.data) {
              total +=item.total
              let attr = {}
              attr.name = item.name
              attr.value = item.total
              this.WaterTotalRankingdata.push(attr)
            }
            this.watermeter.day = total.toFixed(1)
          }
        },
      })
    },
    //获取设备总数
    getProbeTotaldata() {
      ajax.get({
        url: this.$API.getProbeTotal + this.$store.getters.user.id,
        success: (res) => {
          this.prodnum = res.data

        },
      })
    },
    //获取设备操作次数
    getOperationTotaldata() {
      ajax.get({
        url: this.$API.getOperationTotal + this.$store.getters.user.id,
        success: (res) => {
          this.operationTotal = res.data.OperationTotal
        },
      })
    },
    //用电排行
    getelerankdata() {

      let optionsObj = {
        yValueList: [],
        series: [],
      };
      let data = this.isele==0?[...this.proportiondata.series]:[...this.WaterTotalRankingdata]
      console.log(data)
      data.sort((n1, n2) => {
        return n1.value - n2.value;
      });
      for (let item of data) {
        optionsObj.yValueList.push(item.name)
        optionsObj.series.push(item.value)
      }
      this.elerankChart("eleRanking", optionsObj);
    },
    elerankChart(id, optionsObj) {
      let myChart = echarts.init(document.getElementById(id));
      let option = {
        grid: {
          left: "2%",
          right: "10%",
          bottom: "3%",
          top: "9%",
          containLabel: true,
        },
        legend: {
          show: true,
          icon: "circle",
          textStyle: {
            color: "#fff",
            fontWeight: "normal",
          },
          right: "3%",
          top: "5%",
        },
        tooltip: {
          show: true,
        },

        yAxis: {
          type: "category",
          axisLine: {
            show: false,
            lineStyle: {
              color: "#123d72",
              width: "1",
            },
          },
          show: true,
          axisLabel: {
            show: true,
            fontSize: 14,
            color: "rgba(255, 255, 255, 1)",
            formatter: function (name) {
              return (name.length > 6 ? (name.slice(0, 6) + "...") : name);
            },
          },
          axisTick: {
            show: false,
            alignWithLabel: false,
          },
          data: optionsObj.yValueList,
        },
        xAxis: {
          type: "value",
          axisLine: {
            show: false,
            lineStyle: {
              color: "#fff",
            },
          },
          show: false,
          axisLabel: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: "#123d72",
            },
          },
          axisTick: {
            show: false,
          },
        },
        series: [
          {
            data: optionsObj.series,
            type: "bar",
            label: {
              show: true,
              position: "right",
              color: "#fff",
              fontSize: 14,
            },
            barWidth: 26,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: "#00c9d6" },
                { offset: 1, color: "#0099e9" },
              ]),
            },
          },
        ],
      };
      myChart.clear();
      myChart.setOption(option);
    },
    //七天用电量
    getweekeledata() {
      let endDate = getFormatDatezhuanh(new Date()).slice(0, 10)
      let startDate = getFormatDatezhuanh(new Date(new Date() - (24 * 60 * 60 * 1000 * 7))).slice(0, 10)
      let self = this
      let formData = new FormData();
      formData.append('startDate', startDate);
      formData.append('endDate', endDate);
      axios.post(this.$API.getWorkTimeEleByDate + this.$store.getters.user.id, formData).then(function (res) {
        let response = res.data;
        console.log(response)
        let optionsObj = {
          xValueList: [
          ],
          series: [[], []],
        };
        for (let item of response.data) {
          optionsObj.xValueList.push(item.date.slice(5, 10))
          optionsObj.series[0].push((item.workTimeEle / 1000).toFixed(1))
          optionsObj.series[1].push((item.noWorkTimeEle / 1000).toFixed(1))
        }
        self.weekeleChart("weekele", optionsObj);
      })

    },
    weekeleChart(id, optionsObj) {
      let myChart = echarts.init(document.getElementById(id));
      let option = {
        grid: {
          left: "1%",
          right: "1%",
          bottom: "0%",
          top: "20%",
          containLabel: true,
        },
        legend: {
          show: true,
          icon: "rect",
          textStyle: {
            color: "#fff",
            fontWeight: "normal",
          },
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 24.5,
          right: "0%",
          top: "0%",
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'none'
          }
        },
        dataZoom: [{ type: "inside", start: 0, end: 100, minSpan: 0 }],
        xAxis: {
          type: "category",
          axisLine: {
            lineStyle: {
              color: "#123d72",
              width: "1",
            },
          },

          axisLabel: {
            show: true,
            fontSize: 14,
            color: "rgba(255, 255, 255, 1)",
          },
          axisTick: {
            show: false,
            alignWithLabel: true,
          },
          data: optionsObj.xValueList,
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
            lineStyle: {
              color: "#fff",
            },
          },
          axisLabel: {
            show: true,
          },
          splitLine: {
            lineStyle: {
              color: "#123d72",
            },
          },
          axisTick: {
            show: false,
          },
        },
        series: [
          {
            name: '工作时间',
            data: optionsObj.series[0],
            type: "bar",
            stack: 'total',
            label: {
              show: false,
              position: "top",
              color: "#2C98F7",
            },
            barWidth: 20,
            itemStyle: {
              color: '#1285F0',
            },
          },
          {
            name: '非工作时间',
            data: optionsObj.series[1],
            type: "bar",
            stack: 'total',
            label: {
              show: false,
              position: "top",
              color: "#2C98F7",
            },
            barWidth: 20,
            itemStyle: {
              color: '#FCD403',
            },
          },
        ],
      };
      myChart.clear();
      myChart.setOption(option);
    },
    // 工作占比echarts
    getworkele() {
      let time = getFormatDatezhuanh(new Date()).slice(0, 10)
      let self = this
      const formData = new FormData();
      formData.append('time', time);
      axios.post(this.$API.getNotWorkTimeEle + this.$store.getters.user.id, formData).then(function (res) {
        let response = res.data;
        console.log(response)
        let optionsObj = {
          series: [
            {
              value: (response.data.noWorkTimeEle / 1000).toFixed(1),
              name: "非工作时间用电量",
            },
            {
              value: (response.data.workTimeEle / 1000).toFixed(1),
              name: "工作时间用电量",
            },
          ],
          total: (response.data.totalEle / 1000).toFixed(1),
        };
        self.workeleChart("workele", optionsObj);
      });

    },
    workeleChart(id, dataObj) {
      let myChart = echarts.init(document.getElementById(id));
      let option = {
        color: ["#FDD404", "#1386F2"],

        grid: {
          left: "0%",
          right: "3%",
          bottom: "0%",
          top: "0%",
          containLabel: false,
        },
        series: [
          {
            name: "设备数统计",
            radius: ["38%", "55%"],
            type: "pie",
            top: "-10%",
            left: "center",
            height: 340,
            width: 359,
            labelLine: {
              length: 7,
              length2: 10,
              showAbove: true,
            },

            label: {
              textStyle: {
                fontSize: 12,
              },
              formatter: function (params) {
                let str =
                  "{a|" + params.value + "kW·h}\n{b|" + params.name + "}";
                return str;
              },
              rich: {
                a: {
                  color: "#fff",
                  fontSize: 18,
                  align: "center",
                },
                b: {
                  align: "center",
                  color: "#fff",
                  fontSize: 12,
                  fontWeight: 300,
                },
              },
            },
            data: dataObj.series, //数据
          },

          // 显示设备总数
          {
            name: "设备数统计",
            radius: ["38%", "55%"],
            type: "pie",

            top: "-10%",
            left: "center",
            height: 340,
            width: 359,
            label: {
              textStyle: {
                color: "#fff",
                fontSize: 14,
              },

              position: "center",
              formatter: function () {
                let str = "{a|" + dataObj.total + "}{c| }\n{b|总用电量(kW·h)}";
                return str;
              },
              rich: {
                a: {
                  color: "#FF8149",
                  fontSize: 30,
                  lineHeight: 50,
                  align: "center",
                },
                b: {
                  align: "center",
                  color: "#fff",
                  fontSize: 14,

                  fontWeight: 300,
                },
                c: {
                  align: "center",
                  color: "#FF8149",
                  fontSize: 14,

                  fontWeight: 300,
                },
              },
            },
            data: dataObj.series,
          },
        ],
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },

    //用水切换
    getwatermeterdata() {
      let type = null
      let startDay, endDay, data
      switch (this.Dateperiod) {
        case 'week':
          data = getWeekopandend(new Date())
          type = 1
          break;
        case 'month':
          data = getMonthopandend(new Date())
          type = 1
          break;
        case 'year':
          data = [new Date().getFullYear() + '-01-01', new Date().getFullYear() + '-12-31']
          type = 3
          break;
      }
      startDay = data[0].slice(0, 10)
      endDay = data[1].slice(0, 10)
       // let optionsObj = {
      //   xValueList: [],
      //   series: []
      // }
      let optionsObj = {
        xValueList: ['03-27','03-28','03-29','03-30','03-31','04-01','04-02','04-03'],
        series: [846.3,833.2,630.8,413.3,672.2,552.1,359.3,238.2],
      };
      this.watermeterchart("watermeter", optionsObj); 
      // let optionsObj = {
      //   xValueList: [],
      //   series: []
      // }
      // let url = this.isele == 0 ? this.$API.getEleAllByDay : this.$API.getWaterTotal
      // ajax.get({
      //   url: url + this.$store.getters.user.id + `?end=${endDay}&start=${startDay}&type=${type}`,
      //   success: (res) => {
      //     let resp = res.data
      //     let keys = type == 3 ? Object.keys(resp) : Object.keys(resp).reverse();
      //     for (let item in keys) {
      //       if (type == 3) {
      //         optionsObj.xValueList.push(keys[item] + '月')
      //       }
      //       else {
      //         optionsObj.xValueList.push(keys[item].slice(5, 10))
      //       }
      //       if (keys[item] == getFormatDatezhuanh(new Date()).slice(0, 10) && this.isele == 0) {
      //         optionsObj.series.push(this.electricity.day)
      //       }
      //       else {
      //         optionsObj.series.push(this.isele == 0 ? (resp[keys[item]] / 1000).toFixed(1) : resp[keys[item]])
      //       }

      //     }
      //     this.watermeterchart("watermeter", optionsObj);

      //   },
      // })
    },
    //折线图
    watermeterchart(id, optionsObj) {
      let myChart = echarts.init(document.getElementById(id));
      let option = {
        grid: {
          left: "2%",
          right: "5%",
          bottom: "0%",
          top: "9%",
          containLabel: true,
        },
        legend: {
          show: true,
          icon: "circle",
          textStyle: {
            color: "#fff",
            fontWeight: "normal",
          },
          right: "3%",
          top: "5%",
        },
        tooltip: {
          show: true,
          axisPointer: {
            type: "line",
            lineStyle: {
              color: "rgba(253,186,43, 0.3)",
            },
          },

          trigger: "axis",
        },
        xAxis: {
          type: "category",
          axisLine: {
            lineStyle: {
              color: "#123d72",
              width: "1",
            },
          },

          axisLabel: {
            show: true,
            color: "rgba(255, 255, 255, 1)",
          },
          boundaryGap: false,
          axisTick: {
            show: true,
            length: 8,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#123d72",
            },
          },
          data: optionsObj.xValueList,
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
            lineStyle: {
              color: "#fff",
            },
          },

          axisLabel: {
            show: true,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#123d72",
            },
          },
          axisTick: {
            show: true,
            inside: true,
            lineStyle: {
              color: "#123d72",
            },
          },
        },
        dataZoom: [{ type: "inside", start: 0, end: 100, minSpan: 0 }],
        series: [
          {
            data: optionsObj.series,
            type: "line",
            smooth: true,
            showSymbol: true,
            itemStyle: {
              color: "rgba(110,254,227,1)",
            },
            label: {
              show: true,
              position: "top",
            },
            areaStyle: {
              // 折现下是否填充
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(110,254,227,0.6)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(0,168,255,0)", // 100% 处的颜色
                  },
                ],
                global: false,
              },
            },
          },

        ],
      };
      myChart.clear();
      myChart.setOption(option);
    },
    //占比
    //工作占比echarts
    geproportiondata() {
      let optionsObj = []
      ajax.get({
        url: this.$API.getCentralData + this.$store.getters.user.id,
        success: (res) => {
          let resp = res.data
          if (resp.length > 0) {
            this.proportiondata.series = []
            let dayeletotal = 0
            for (let item of resp) {
              dayeletotal += parseFloat(item.ele)
              let attr = {}
              attr.name = item.organName
              attr.value = (item.ele / 1000).toFixed(1)
              attr.opprod = item.open
              attr.allprod = item.total
              this.proportiondata.series.push(attr)
            }
            this.electricity.day = (dayeletotal / 1000).toFixed(1)
            this.getEleAlldata()
            optionsObj = this.proportiondata
            this.proportionChart("proportion", optionsObj);
            this.getproportionOption()
            //调用其他
            this.getelerankdata();
            this.getwatermeterdata();
            clearInterval(proptime)
            proptime = setInterval(() => {

              this.getproportionOption()
            }, 60000);
          }
          else {
            optionsObj = []
            clearInterval(proptime)
            this.proportionChart("proportion", optionsObj);
          }
        },
      })

    },
    proportionChart(id, dataObj) {
      proportion = echarts.init(document.getElementById(id));
      let option = {
        color: color,

        grid: {
          left: "0%",
          right: "0%",
          bottom: "0%",
          top: "0%",
          containLabel: false,
        },
        series: [
          {
            radius: ["65%", "85%"],
            type: "pie",
            top: "-17.8%",

            itemStyle: {
              borderColor: "#0C1359",
              borderWidth: 10,

            },
            avoidLabelOverlap: true,
            // startAngle:60,
            labelLine: {
              // length: 30,
              // minTurnAngle:180,

            },
            stillShowZeroSum: true,
            minShowLabelAngle: 1,
            label: {
              textStyle: {
                fontSize: 14,
              },
              position: 'inside',
              borderColor: '#3E4567',
              // borderWidth: 1,
              // padding: [5,10],
              show: true,
              overflow: "breakAll",
              formatter: function (params) {
                //console.log(params)
                let str =
                  "{a|" + params.name + "}" + "\n{b|" + params.percent + "%}";
                return str;
              },
              rich: {
                a: {
                  color: "#fff",
                  fontSize: 18,
                  align: "center",
                  fontWeight: 300,

                  lineHeight: 25
                },
                b: {
                  align: "center",
                  color: "#fff",
                  fontSize: 18,
                  fontWeight: 300,
                  lineHeight: 20
                },
                c: {
                  align: "right",
                  color: "#00c800",
                  fontSize: 16,
                  fontWeight: 300,
                  lineHeight: 25
                },
              },
            },
            data: dataObj.series, //数据
          },
        ],
      };
      proportion.setOption(option);
      window.addEventListener("resize", function () {
        proportion.resize();
      });
      proportion.on("mouseover", (e) => {
        clearInterval(proptime)
        proptime = null
        let op = proportion.getOption();
        let arrcolor = []
        this.overviewdata = this.proportiondata.series[e.dataIndex]
        //console.log(this.proportiondata.series,e.dataIndex,this.overviewdata)
        this.overviewwavetop = 3.13 - 3.13 * (this.overviewdata.opprod / this.overviewdata.allprod)

        for (let i = 0; i < this.proportiondata.series.length; i++) {
          if (i == e.dataIndex) {
            arrcolor.push(colorhover[e.dataIndex % 5])
          } else {
            arrcolor.push(color[i % 5])
          }
        }
        op.color = arrcolor
        proportion.setOption(op, true);

      });
      proportion.on("mouseout", (e) => {
        this.proportionindex = this.proportionindex > 0 ? this.proportionindex-- : 0

        this.getproportionOption()
        clearInterval(proptime)
        proptime = null
        proptime = setInterval(() => {

          this.getproportionOption()
        }, 60000);
      });
    },
    getproportionOption() {
      let op = proportion.getOption();
      let arrcolor = []
      for (let i = 0; i < this.proportiondata.series.length; i++) {
        if (i == this.proportionindex) {
          arrcolor.push(colorhover[this.proportionindex % 5])
        } else {
          arrcolor.push(color[i % 5])
        }
      }

      this.overviewdata = this.proportiondata.series[this.proportionindex]
      //console.log(this.proportiondata.series,this.proportionindex,this.overviewdata )
      this.overviewwavetop = 3.13 - 3.13 * (this.overviewdata.opprod / this.overviewdata.allprod)
      if (this.proportionindex > this.proportiondata.series.length - 2) {
        this.proportionindex = 0
      } else {
        this.proportionindex++
      }
      op.color = arrcolor
      proportion.setOption(op, true);
      // console.log(proportion.getOption())
    }
  },
};

//时间格式化
function getFormatDatezhuanh(nowDate) {
  let date = nowDate
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  let hours = date.getHours()
  let minutes = date.getMinutes()
  let seconds = date.getSeconds()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate < 10) {
    strDate = '0' + strDate
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minutes < 10) {
    minutes = '0' + minutes
  }
  if (seconds < 10) {
    seconds = '0' + seconds
  }
  let currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds
  // console.log(currentDate)
  return currentDate
}
//获取当前周的开始和结束
function getWeekopandend(time) {
  let dayCode = new Date(time).getDay();

  let dayLong = 24 * 60 * 60 * 1000;
  let startDay = getFormatDatezhuanh(new Date(dayCode === 0 ? time - dayLong * 7 : time - dayLong * (dayCode - 1)))
  let endDay = getFormatDatezhuanh(new Date(dayCode === 0 ? time : time.getTime() + dayLong * (7 - dayCode)))

  return [startDay, endDay]
}
//获取当前月的开始和结束
function getMonthopandend(time) {
  let date = new Date(time)
  let startDay = getFormatDatezhuanh(new Date(date.setDate(1))); //本月第一天
  let endDay = getFormatDatezhuanh(new Date(date.getFullYear(), date.getMonth() + 1, 0))//本月的最后一天

  return [startDay, endDay]
}
